import { defineStore } from 'pinia';
import { useUserStore } from './user';
import { 
    getProblemList, 
    getProblemDetail,
    submitSolution,
    getSubmissionDetail,
    getSubmissions,
    getUserProblems
} from '../api/problem';
import { message } from 'ant-design-vue';

export const useProblemStore = defineStore('problem', {
  state: () => ({
    problems: [], // 题目列表
    currentProblem: null, // 当前查看的题目
    currentSubmission: null, // 当前提交结果
    loading: false,
    error: null,
    pagination: {
      page: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true
    },
    cachedProblems: new Map() // 题目缓存
  }),

  actions: {
    /**
     * 获取题目列表
     * @param {Object} params 查询参数
     * @param {number} params.page 页码
     * @param {number} params.pageSize 每页数量
     * @param {string} [params.difficulty] 难度筛选
     * @param {string[]} [params.tags] 标签筛选
     */
    async fetchProblemList(params = {}) {
      this.loading = true;
      try {
        const { problems, total } = await getProblemList({
          page: params.page || 1,
          pageSize: params.pageSize || 10,
          difficulty: params.difficulty || 0,
          solvedStatus: params.solvedStatus || 0,
          sortBy: params.sortBy || 1,
          searchQuery: params.searchQuery || ''
        });
        this.problems = problems.map(p => ({
          problemId: p.problemId,
          problemTitle: p.problemTitle,
          difficultyLevel: p.difficulty,
          acceptanceRate: p.acceptanceRate.toFixed(2)
        }));
        this.pagination = {
          page: params.page,
          pageSize: params.pageSize,
          total
        };

        // 缓存题目数据
        problems.forEach(problem => {
          this.cachedProblems.set(problem.id, problem);
        });

        return problems;
      } catch (error) {
        this.error = error;
        message.error(error.message || '获取题目列表失败');
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 获取题目详情
     * @param {string} id 题目ID
     */
    async fetchProblemDetail(id) {
      this.loading = true;
      try {
        // 检查缓存
        if (this.cachedProblems.has(id)) {
          this.currentProblem = this.cachedProblems.get(id);
          return this.currentProblem;
        }
        // 调用API获取题目详情
        const problem = await getProblemDetail(id);
        
        this.currentProblem = problem;
        this.cachedProblems.set(id, problem);

        return problem;
      } catch (error) {
        this.error = error;
        message.error(error.message || '获取题目详情失败');
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 提交题目解答
     * @param {Object} params 提交参数
     * @param {string} params.problemId 题目ID
     * @param {string} params.language 编程语言
     * @param {string} params.code 代码内容
     */
    async submitSolution(params) {
      this.loading = true;
      try {
        const result = await submitSolution(params);
        if (result.success == false) {
          return {
            accepted: false,
            message : "提交失败，服务器内部错误"
          }
        }
        return result.result;
      } catch (error) {
        this.error = error;
        message.error(error.message || '提交失败');
        throw error;
      } finally {
        this.loading = false;
      }
    },
    /**
     * 获取提交记录的列表信息
     * @param {string} id 题目的id
     * @param {int} page 页数
     * @param {int} pagesize 页数的大小 
     * @returns {list, total} list是数据的列表，total是总数据的大小
     */
    async fetchSubmissions(id, page, pagesize){
      // 
      try{
        const result = await getSubmissions(id,page,pagesize);
        if (result.success)
          return result.result;
        throw "请求失败";
      }catch(error) {
        console.log('获取提交记录的信息列表失败',error);
        return {
          list: [],
          total: 0
        }
      }
    },
    /**
     * 获取提交记录详细信息
     * @param {string} id 题目的id
     * @returns 提交记录的详细内容
     */
    async fetchSubmissionDetail(id){
      // 
    try{
      const result = await getSubmissionDetail(id);
      if (result.success){
        return result.result;
      }
      throw "请求失败";
    }catch(error) {
      console.log('获取提交记录信息失败',error);
      return {}
    }
    },async getSolvedProblems(userId, page = 1, pageSize = 10) {
        try {
          const res = await getUserProblems(userId, true, page, pageSize);
          return res;
        } catch (error) {
          console.error('获取已通过题目失败:', error);
          return { 
            problems: [],
            page,
            pageSize,
            totalPages: 0
          };
        }
      },
    
      async getAttemptingProblems(userId, page = 1, pageSize = 10) {
        try {
          const res = await getUserProblems(userId, false, page, pageSize);
          return res;
        } catch (error) {
          console.error('获取尝试中题目失败:', error);
          return { 
            problems: [], 
            page,
            pageSize,
            totalPages: 0
          };
        }
      }
  },
  

  getters: {
    /**
     * 根据ID获取题目
     * @param {string} id 题目ID
     * @returns {Problem|null}
     */
    getProblemById: (state) => (id) => {
      return state.cachedProblems.get(id) || null;
    },

    /**
     * 检查题目是否已解决
     * @param {string} id 题目ID
     * @returns {boolean}
     */
    isProblemSolved: (state) => (id) => {
      const userStore = useUserStore();
      return userStore.isProblemSolved(id);
    }
  }
});
